<script setup>
import { onMounted, nextTick, ref, reactive, watch, toRefs, computed, onUnmounted, watchEffect } from 'vue'
import Config from '../mapInfoObj/mapConfig'
import { mapObj } from '../mapInfoObj/initMap'
import * as turf from '@turf/turf'
import Html2canvas from "html2canvas";
import axios from 'axios';
import { ElLoading, ElMessage } from 'element-plus'
import { resetLayer, addArrow, clearArrow } from '../mapInfoObj/initMap'
import mitt from '@/assets/js/mitt'
import { useIfwindParticle } from '@/stores/default'
const IfwindParticle = useIfwindParticle()

const urlGif = import.meta.env.VITE_backurl_gif

const emit = defineEmits(['handleMapEvent'])
onMounted(() => {
  mitt.on('closeArrow', () => {
    // mapObj.map.off('zoomend', renderArrow)
    isLang.value = false
    isDeng.value = false
  })
})
const handleBasicTool = (name) => {
  switch (name) {
    case '等值面':
      (() => {
        if (!Config.curData?.wave && !Config.curData?.surge) {
          ElMessage.warning('未加载数据')
          isDeng.value = false
          return
        }
        if (mapObj.currentLine.length) {
          mapObj.currentLine.forEach(line => {
            Config.ToolLayers.removeLayer(line)
          })
          mapObj.currentLine = []
          return
        }
        breakDialog.value = true
      })()
      break;
    case '浪向':
      // wavaArrow()
      (() => {
        console.log(isLang.value);
        isLang.value = !isLang.value
      })()
      break;
    default:
      break;
  }
}


let currentLine = []
mapObj.currentLine = currentLine
// 绘制等值面
const isosurface = () => {
  breakDialog.value = false
  let { startLat, startLon, vscale, uscale } = Config.rasterHeader['global']
  let extent = [Config.rasterHeader.global.startLon, Config.rasterHeader.global.endLat, Config.rasterHeader.global.endLon, Config.rasterHeader.global.startLat]
  var cellWidth = 10;
  var pointGrid = turf.pointGrid(extent, cellWidth, { units: 'miles' });
  for (var i = 0; i < pointGrid.features.length; i++) {
    let row = Math.floor((startLat - pointGrid.features[i].geometry.coordinates[1]) / vscale)
    let col = Math.floor((pointGrid.features[i].geometry.coordinates[0] - startLon) / uscale)
    if (Config.curData?.wave) {
      pointGrid.features[i].properties.wavaValue = Config.curData?.wave[row][col].value
    } else if (Config.curData?.surge) {
      pointGrid.features[i].properties.wavaValue = Config.curData?.surge[row][col].value
    }
    // pointGrid.features[i].properties.wavaValue = Config.curData?.wave[row][col].value
  }
  // var breaks = [0, 0.5, 1, 1.5, 2, 2.5];
  // var breaks = [0, 5, 10, 15, 20, 25];
  let breaks = breaksRef.value.map(item => {
    return item.value
  })
  var lines = turf.isolines(pointGrid, breaks, { zProperty: 'wavaValue' });
  lines.features.forEach((lineType, linTypeIdx) => {
    lineType.geometry.coordinates.forEach((line, lineIdx) => {
      let latlngs = []
      line.forEach(point => {
        latlngs.push([point[1], point[0]])
      })

      // var linePh = turf.lineString(line);
      // var curved = turf.bezierSpline(linePh);
      // let latlngs = []
      // curved.geometry.coordinates.forEach(point => {
      //   latlngs.push([point[1], point[0]])
      // })
      // let color=Config.scalarColor.wave[linTypeIdx].color
      // let color = 'red'
      let color = breaksRef.value[linTypeIdx].color
      let lineC = L.polyline(latlngs, {
        color: color,
        weight: 1,
      }).addTo(Config.ToolLayers)
      mapObj.currentLine.push(lineC)
    })
  })

  resetLayer()
  // resetLayer()
}

// let isArrow = false
const wavaArrow = () => {
  if (!Config.curData?.wave && isLang.value) {
    ElMessage.warning('未加载海浪数据')
    isLang.value = false
    return
  }
  // if (!Config.curData?.surge) {
  //   ElMessage.warning('未加载潮汐数据')
  //   return
  // }

  if (!isLang.value) {
    clearArrow()
    mapObj.map.off('zoomend', renderArrow)
    return
  }


  renderArrow()
  // isArrow = true
  // 监听地图缩放
  mapObj.map.on('zoomend', renderArrow)
}

const renderArrow = () => {
  clearArrow()
  let step = Math.floor(100 / mapObj.map.getZoom()) * 5
  for (let row = 0; row < Config.curData?.wave.length; row = row + step) {
    for (let col = 0; col < Config.curData?.wave[row].length; col = col + step) {
      if (Config.curData?.wave[row][col] == -999) continue
      let data = {
        lat: Config.rasterHeader.global.startLat - row * Config.rasterHeader.global.vscale,
        lng: Config.rasterHeader.global.startLon + col * Config.rasterHeader.global.uscale,
        angle: Config.curData?.wave[row][col].angle,
      }
      addArrow(data)
    }
  }
  // resetLayer()
}


const breaksRef = ref([
  {
    color: 'red',
    value: 0
  },
  {
    color: 'red',
    value: 5
  },
  {
    color: 'red',
    value: 10
  },
  {
    color: 'red',
    value: 15
  },
  {
    color: 'red',
    value: 20
  },
  {
    color: 'red',
    value: 25
  },
]),
  breakDialog = ref(false)


const handleAdd = () => {
  breaks.value.push({
    color: 'red',
    value: 0
  })
},
  handleDel = () => {
    breaks.value.pop()
  }

onUnmounted(() => {
  mapObj.map.off('zoomend', renderArrow)

})

const isValue = ref(false), isDeng = ref(false), isLang = ref(false), iswindParticle = ref(true)

watch(isLang, () => { wavaArrow() })

watch(isDeng, () => {
  if (!Config.curData?.wave && isDeng.value) {
    ElMessage.warning('未加载数据')
    isDeng.value = false
    return
  }
  if (!isDeng.value) {
    mapObj.currentLine.forEach(line => {
      Config.ToolLayers.removeLayer(line)
    })
    mapObj.currentLine = []
    return
  }
  breakDialog.value = true
})

watch(isValue, (val) => {
  for (let key of ['surgeLayer', 'waveLayer', 'tideLayer', 'windLayer']) {
    Config.AllLayers[key].setShowLabel(val)
  }
})

watch(iswindParticle, (val) => {
  IfwindParticle.setValue(val)
  if (val) {
    Config.AllLayers.windParticleLayer.addTo(mapObj.map)
  } else {
    if (mapObj.map.hasLayer(Config.AllLayers.windParticleLayer)) {
      mapObj.map.removeLayer(Config.AllLayers.windParticleLayer)
    }
  }
})
</script>

<template>
  <div class="KaiGuan">
    <el-switch
      inline-prompt
      v-model="isValue"
      active-text="数值"
      inactive-text="数值"
      size="large"
    />
    <!-- <el-switch
      inline-prompt
      v-model="iswindParticle"
      active-text="粒子"
      inactive-text="粒子"
      size="large"
    /> -->
  </div>

  <el-dialog
    width="30%"
    v-model="breakDialog"
    :destroy-on-close="true"
    :show-close="false"
    top="30vh"
    title="选择等值面断点"
    :modal="true"
    :close-on-click-modal="false"
  >
    <!-- 默认填5个级别，也可以增加可删除级别 -->
    <el-row v-for="item in breaksRef" :gutter="20">
      <el-col :span="9">
        <el-color-picker v-model="item.color"></el-color-picker>
        {{ item.color }}
      </el-col>
      <el-col :span="9">
        <el-input v-model="item.value" placeholder=""></el-input>
      </el-col>
      <el-col :span="6">
        <el-button size="" @click="handleAdd">+</el-button>
        <el-button size="" @click="handleDel">-</el-button>
      </el-col>
    </el-row>

    <!-- foot isDeng-->
    <template #footer>
      <span class="dialog-footer">
        <el-button
          @click="
            () => {
              breakDialog = false
              isDeng = false
            }
          "
          >取消</el-button
        >
        <el-button type="primary" @click="isosurface"> 确定 </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style lang='less' scoped>
.el-row {
  margin-bottom: 10px;

  :deep(.el-date-editor) {
    max-width: 100% !important;
  }
}

.KaiGuan {
  position: absolute;
  // bottom: 20px;
  top: 130px;
  right: 10px;
  z-index: 499;
  display: flex;
  flex-direction: column;

  .el-switch {
    margin: 10px;
  }
}
</style>